/**
 * 
 */
package com.xinghou.platform.file.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.xinghou.platform.file.chain.exception.AuthenticationException;
import com.xinghou.platform.file.handler.impl.PhotoUploadHandler;
import com.xinghou.platform.file.handler.impl.UpPhotoHandler;
import com.xinghou.platform.file.handler.impl.UpShopPhotoHandler;
import com.xinghou.platform.file.model.ResourceContext;
import com.xinghou.platform.server.mq.MqMessage;
import com.xinghou.platform.util.ConfigUtil;
import com.xinghou.platform.util.JsonUtil;
import com.xinghou.platform.util.SignUtil;

/**
 * @author wxtdy
 * 
 */
@Controller
public class PhotoController extends BaseController {
	private static Logger logger = Logger.getLogger(PhotoController.class);

	@Resource
	private PhotoUploadHandler photoUploadHandler;
	@Resource
	private UpPhotoHandler upPhotoHandler;
	@Resource
	private UpShopPhotoHandler upShopPhotoHandler;
	
	@Resource
	private MqMessage mqMessage;

	private String key = ConfigUtil.getProperty("HTTP_SERVICE_KEY");

	/**
	 * 头像上传方法
	 * 
	 * @author xuzhen
	 */
	@RequestMapping(value = "/server/api/upPhoto", method = RequestMethod.PUT)
	public ResponseEntity<String> upPhoto(
			@RequestHeader(value = "Content-Type", required = true) String contentType,
			@RequestHeader(value = "Content-Length", required = true) Integer contentLength,
			@RequestHeader(value = "User-Agent", required = false) String userAgent,
			@RequestParam(value = "sign", required = true) String sign,
			@RequestParam(value = "userid", required = true) String userid,
			@RequestParam(value = "phototype", required = true) String phototype,
			@RequestParam(value = "appversion", required = true) String appversion,
			@RequestBody byte[] body, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, String> requestContent = new HashMap<String, String>();
		requestContent.put("userid", userid);
		requestContent.put("phototype", phototype);
		requestContent.put("appversion", appversion);

		if (sign.equals(SignUtil.createSign(
				new TreeMap<String, String>(requestContent), key).toString())) {
			ResourceContext<byte[], String> context = new ResourceContext<byte[], String>(
					1);
			context.getRequest().setResourceType(101);
			context.getRequest().setToken(sign);
			context.getRequest().setBody(body);
			context.getRequest().setUserId(userid);
			context.getRequest().setShareid("");
			try {
				upPhotoHandler.execute(context);
				ResponseEntity<String> reponse = context.response();
				return reponse;
			} catch (RuntimeException e) {
				logger.error("头像上传失败", e);
				return new ResponseEntity<String>(
						HttpStatus.INTERNAL_SERVER_ERROR);
			} catch (Exception e) {
				if (e instanceof AuthenticationException) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("result", "1");
					map.put("errmsg", "token Invalid!");
					HttpHeaders header = new HttpHeaders();
					header.set("Content-Type", "application/json;charset=UTF-8");
					return new ResponseEntity<String>(JsonUtil.toJson(map),
							header, HttpStatus.OK);
				} else {
					return new ResponseEntity<String>(
							HttpStatus.INTERNAL_SERVER_ERROR);
				}
			} finally {
				context.clear();
				context = null;
			}
		} else {
			Map<String, String> map = new HashMap<String, String>();
			map.put("result", "1");
			map.put("errcode", "140");
			map.put("errmsg", "签名失败");
			HttpHeaders header = new HttpHeaders();
			header.set("Content-Type", "application/json;charset=UTF-8");
			return new ResponseEntity<String>(JsonUtil.toJson(map), header,
					HttpStatus.OK);
		}

	}

	/**
	 * 分享图片上传方法
	 * 
	 * @author xuzhen
	 */
	@RequestMapping(value = "/server/api/upPhotoShare", method = RequestMethod.PUT)
	public ResponseEntity<String> upPhotoShare(
			@RequestHeader(value = "Content-Type", required = true) String contentType,
			@RequestHeader(value = "Content-Length", required = true) Integer contentLength,
			@RequestHeader(value = "User-Agent", required = false) String userAgent,
			@RequestParam(value = "sign", required = true) String sign,
			@RequestParam(value = "userid", required = true) String userid,
			@RequestParam(value = "shareid", required = true) String shareid,
			@RequestParam(value = "sharetype", required = true) String sharetype,
			@RequestParam(value = "appversion", required = true) String appversion,
			@RequestBody byte[] body, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, String> requestContent = new HashMap<String, String>();
		requestContent.put("userid", userid);
		requestContent.put("shareid", shareid);
		requestContent.put("sharetype", sharetype);
		requestContent.put("appversion", appversion);

		if (sign.equals(SignUtil.createSign(
				new TreeMap<String, String>(requestContent), key).toString())) {
			ResourceContext<byte[], String> context = new ResourceContext<byte[], String>(
					1);
			context.getRequest().setResourceType(101);
			context.getRequest().setToken(sign);
			context.getRequest().setBody(body);
			context.getRequest().setUserId(userid);
			context.getRequest().setShareid(shareid);
			context.getRequest().setSharetype(sharetype);
			try {
				upPhotoHandler.execute(context);
				return context.response();
			} catch (RuntimeException e) {
				return new ResponseEntity<String>(
						HttpStatus.INTERNAL_SERVER_ERROR);
			} catch (Exception e) {
				if (e instanceof AuthenticationException) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("result", "1");
					map.put("errmsg", "token Invalid!");
					HttpHeaders header = new HttpHeaders();
					header.set("Content-Type", "application/json;charset=UTF-8");
					return new ResponseEntity<String>(JsonUtil.toJson(map),
							header, HttpStatus.OK);
				} else {
					return new ResponseEntity<String>(
							HttpStatus.INTERNAL_SERVER_ERROR);
				}
			} finally {
				context.clear();
				context = null;
			}
		} else {
			Map<String, String> map = new HashMap<String, String>();
			map.put("result", "1");
			map.put("errcode", "140");
			map.put("errmsg", "签名失败");
			HttpHeaders header = new HttpHeaders();
			header.set("Content-Type", "application/json;charset=UTF-8");
			return new ResponseEntity<String>(JsonUtil.toJson(map), header,
					HttpStatus.OK);
		}

	}

	/**
	 * 商铺图片上传方法
	 * 
	 * @author xuzhen
	 */
	@RequestMapping(value = "/server/api/upShopImg", method = RequestMethod.PUT)
	public ResponseEntity<String> upShopImg(
			@RequestHeader(value = "Content-Type", required = true) String contentType,
			@RequestHeader(value = "Content-Length", required = true) Integer contentLength,
			@RequestHeader(value = "User-Agent", required = false) String userAgent,
			@RequestParam(value = "sign", required = true) String sign,
			@RequestParam(value = "userid", required = true) String userid,
			@RequestParam(value = "shopid", required = true) String shopid,
			@RequestParam(value = "imgtype", required = true) String imgtype,
			@RequestParam(value = "appversion", required = true) String appversion,
			@RequestBody byte[] body, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, String> requestContent = new HashMap<String, String>();
		requestContent.put("userid", userid);
		requestContent.put("shopid", shopid);
		requestContent.put("imgtype", imgtype);
		requestContent.put("appversion", appversion);

		if (sign.equals(SignUtil.createSign(
				new TreeMap<String, String>(requestContent), key).toString())) {
			ResourceContext<byte[], String> context = new ResourceContext<byte[], String>(
					1);
			context.getRequest().setResourceType(101);
			context.getRequest().setToken(sign);
			context.getRequest().setBody(body);
			context.getRequest().setUserId(userid);
			context.getRequest().setShopid(shopid);
			context.getRequest().setImgtype(imgtype);
			try {
				upShopPhotoHandler.execute(context);
				return context.response();
			} catch (RuntimeException e) {
				return new ResponseEntity<String>(
						HttpStatus.INTERNAL_SERVER_ERROR);
			} catch (Exception e) {
				if (e instanceof AuthenticationException) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("result", "1");
					map.put("errmsg", "token Invalid!");
					HttpHeaders header = new HttpHeaders();
					header.set("Content-Type", "application/json;charset=UTF-8");
					return new ResponseEntity<String>(JsonUtil.toJson(map),
							header, HttpStatus.OK);
				} else {
					return new ResponseEntity<String>(
							HttpStatus.INTERNAL_SERVER_ERROR);
				}
			} finally {
				context.clear();
				context = null;
			}
		} else {
			Map<String, String> map = new HashMap<String, String>();
			map.put("result", "1");
			map.put("errcode", "140");
			map.put("errmsg", "签名失败");
			HttpHeaders header = new HttpHeaders();
			header.set("Content-Type", "application/json;charset=UTF-8");
			return new ResponseEntity<String>(JsonUtil.toJson(map), header,
					HttpStatus.OK);
		}

	}

     
}
